<template>
  <div class="mb-sub-form">
    <template v-if="!readonly">
      <div class="sub-form-cell" id="sub-form"></div>
    </template>
    <!-- 只读模式 -->
    <template v-else>
      <van-cell-group class="sub-form-cell cell-group-readonly">
        <div v-for="(item, index) in meta" :key="index"  class="van-cell van-cell-clear">
          <van-field 
            v-if="item.dataType !== 'Clob'"
            :type="item.xtype === 'textarea'?'textarea':'text'"
            :label="item.caption||item.name" 
            :value="item.defaultValue_display || item.defaultValue" 
            readonly/>
          <div v-else>
            <van-cell :title="item.name"></van-cell>
            <van-card
              v-for="(file, index) in getfiles(item.defaultValue)"
              :key="index"
              :title="file.name"
              style="background-color: #fff;"
            >
              <van-icon slot="thumb" name="description" size="36px" style="line-height: inherit;"/>
              <div slot="desc">
                <span>{{filesize(file.size)}}</span>
                <span style="color: #1989fa;margin-left: 8px" @click="getPreviewFiles(file, item)">预览</span>
              </div>
            </van-card>
          </div>
        </div>
      </van-cell-group>
    </template>
  </div>
</template>

<script>
import {MbCell, MbField, MbSelect, MbSwitcher, MbDatetimePicker, MbUploader} from "mb-vue"
import compiler from "utils/compiler"
import filesize from 'utils/filesize'
import EventManager from 'utils/events'

export default {
  name: 'mb-sub-form',
  props: {
    options: Object,
    readonly: Boolean
  },
  data() {
    return {
      meta: [],
      model: [],
      vm: null,
      formData: {},
      filesize: filesize,
      eventMgr: null
    }
  },
  computed: {
    title() {
      return this.options.name || ''
    }
  },
  watch: {
    // ...
  },
  methods: {
    /**
     * 显示某些控件
     * @param  {Array} ids 控件id数组
     */
    showItem (ids) {
      const vm = this.vm.$refs[ids[0]];
      vm.visible = true;
    },
    /**
     * 隐藏某些控件
     * @param  {Array} ids 控件id数组
     */
    hideItem (ids) {
      const vm = this.vm.$refs[ids[0]];
      vm.visible = false;
    },
    /**
     * @method requireItem
     * @description 添加字段的必填校验
     * @param {String|Array} ids - 表单字段的name
     */
    requireItem (ids) {
      const vm = this.vm.$refs[ids[0]];
      vm.item.required = true;
    },
    /**
     * @method unRequireItem
     * @description 取消字段的必填校验
     * @param {String|Array} ids - 表单字段的name
     */
    unRequireItem (ids) {
      const vm = this.vm.$refs[ids[0]];
      if(vm.error != null) vm.error = false;
      vm.item.required = false;
    },
    init() {
      if(!this.options.meta) return
      const _this = this;
      // 按照 [options.model] 顺序整合 [meta] 数据顺序,并赋值
      this.model = this.options.options.models;
      this.defaultValue = this.options.defaultValue;
      const metaHash = new Array();
      this.options.meta.forEach( item => {
        item.supportSigns = _this.options.supportSigns;
        item.time = _this.options.time;
        metaHash[item.name] = item
      });
      this.meta = [];
      this.model = this.model.map( item => {
        // 赋值
        if(_this.defaultValue) {
          metaHash[item]["defaultValue"] = _this.defaultValue[item];
          let display = item + "_DISPLAY";
          if(_this.defaultValue[display]) metaHash[item]["defaultValue_display"] = _this.defaultValue[display];
        }
        // 针对“___”开头的变量进行特殊处理
        if(/___/.test(item)){
          let ___meta = metaHash[item];
          item = "N" + item;
          ___meta.nameClone = ___meta.name;
          ___meta.name = item;
          _this.meta.push(___meta);
        } else {
          _this.meta.push(metaHash[item]);
        }
        return item;
      })
      // 只读模式,处理[option.defaultValue]
      if(this.readonly) return;
      // 数据匹配组件
      let components = { MbCell, MbField, MbSelect, MbSwitcher, MbDatetimePicker, MbUploader};
      const vm = compiler(this.options.meta, components, "#sub-form");
      _this.vm = vm;
      _this.formData = vm.formData;
      vm.$on('formdataChange', function (name, values, item) {
        _this.$emit("formdataChange", name, values, item)
        _this.eventMgr.checkEvent('change', name, values)
      })
      // 事件注册
      let properties = {"data": "meta"}
      this.eventMgr = new EventManager(this, properties)
    },
    getfiles(item) {
      let files = [];
      for (var prop in item) {
        let obj = item[prop];
        obj.name = prop;
        files.push(obj);
      }
      return files
    },
    getPreviewFiles(file, meta) {
      let param = "?fileName=" + file.name + "&itemName=" + meta.name;
      if(meta.key && Object.prototype.toString.call(meta.key) === '[object Object]') {
        param += ("&key=" + JSON.stringify(meta.key)) 
      }
      let url = encodeURIComponent(window.contextPath + meta.uploadUrlPre + 'previewFile.do' + param);
      if(/\.png$|\.jpg$|\.jpeg$|\.gif$/.test(file.name)) {
        // 预览图片
        window.vant.ImagePreview({
          showIndex: false,
          images: [url],
          closeOnPopstate: true,
          onClose() {
            this.images = []
          }
        })
      } else {
        // 预览文件
        window.open(url)
      }
    },
    validate() {
      return this.vm.validate()
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style lang="less" scoped>
  .mb-sub-grid {
    background-color: #FFFFFF;
  }
  .sub-grid-header {
    padding: 12px 16px 8px 16px;
  }
  .van-card__thumb {
    height: 36px;
    width: 36px;
    line-height: 36px;
  }
  .van-card__content {
    min-height: 36px;
  }
</style>